package com.hzit.service.impl;

import com.hzit.entity.Student;
import com.hzit.mapper.StudentMapper;
import com.hzit.service.StudentService;
import com.hzit.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.io.IOException;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
public class StudentServiceImpl implements StudentService {

	//1. 查询所有学生
	@Override
	public List<Student> findAll() throws IOException {
		//1.1 得到SqlSessionFactory对象
		SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
		try (SqlSession session = sqlSessionFactory.openSession()) {
			//1.2 得到StudentMapper对象
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			//1.3 开始查询
			List<Student> students = mapper.findAll();
			//1.4 返回结果
			return students;
		}
	}
	//2. 添加学生
	@Override
	public void insert(Student stud) throws IOException {
		//2.1 得到SqlSessionFactory对象
		SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
		try(SqlSession session = sqlSessionFactory.openSession(true)){
			//2.2 得到StudentMapper对象
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			//2.3 添加学生
			mapper.insert(stud);
		}
	}

	//3. 根据学生编号查询学生
	@Override
	public Student findById(int sid) throws IOException {
		//3.1 得到SqlSessionFactory对象
		SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
		try(SqlSession session = sqlSessionFactory.openSession(true)){
			//3.2 得到StudentMapper对象
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			//3.3 查询单个学生
			Student student = mapper.findById(sid);
			//3.4 返回
			return student;
		}
	}

	//4. 修改学生
	@Override
	public void update(Student student) throws IOException {
		//4.1 得到SqlSessionFactory对象
		SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
		try(SqlSession session = sqlSessionFactory.openSession(true)){
			//4.2 得到StudentMapper对象
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			//4.3 修改学生
			mapper.update(student);
		}
	}
}
